package com.tanhua.server.service;

import com.tanhua.manage.domain.db.UserInfo;
import com.tanhua.manage.domain.mongo.RecommendUser;
import com.tanhua.manage.domain.vo.PageResult;
import com.tanhua.manage.domain.vo.RecommendUserQueryParam;
import com.tanhua.manage.domain.vo.RecommendUserVo;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class RecommendUserService2 {

    @Reference
    private RecommendUserApi recommendUserApi;
    @Reference
    private UserInfoApi userInfoApi;


    /**
     * 推荐列表
     * @param queryParam
     * @return
     */
    public PageResult<RecommendUserVo> recommendList(RecommendUserQueryParam queryParam) {
        Long userId = UserHolder.getUserId();
        PageResult result = recommendUserApi.findPage(queryParam.getPage(),queryParam.getPagesize(),userId);
        List<RecommendUser> recommendUserList = result.getItems();
        if (CollectionUtils.isEmpty(recommendUserList)){
            result.setPages(1L);
            result.setCounts(10L);
            recommendUserList = defultRecommend();
        }
        List<Long> userIds = recommendUserList.stream().map(RecommendUser::getUserId).collect(Collectors.toList());

        List<UserInfo> userInfoList = userInfoApi.findByBatchId(userIds);
        Map<Long,UserInfo> userInfoMap = userInfoList.stream().collect(Collectors.toMap(UserInfo::getId,u -> u));

        List<RecommendUserVo> voList = recommendUserList.stream().map(recommendUser -> {

            RecommendUserVo vo = new RecommendUserVo();
            UserInfo userInfo = userInfoMap.get(recommendUser.getUserId());
            BeanUtils.copyProperties(userInfo,vo);
            vo.setTags(StringUtils.split(userInfo.getTags(),","));
            vo.setFateValue(recommendUser.getScore().longValue());
            return vo;
        }).collect(Collectors.toList());

        result.setItems(voList);
        return result;
    }


    /**
    构造默认数据
     */
    private List<RecommendUser> defultRecommend() {
        String ids = "1,2,3,4,5,6,7,8,9,10";

        List<RecommendUser> records = new ArrayList<>();
        for (String id : ids.split(",")) {
            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setUserId(Long.valueOf(id));
            recommendUser.setScore(RandomUtils.nextDouble(70,98));
            records.add(recommendUser);
        }
        return records;
    }
}
